import os
import zipfile

def zip_directory_contents(directory_path, zip_filename):
    try:
        # 创建一个 ZIP 文件
        with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
            # 遍历目录中的所有文件和子目录
            for foldername, subfolders, filenames in os.walk(directory_path):
                # 构建 ZIP 文件中的相对路径
                arcname = os.path.relpath(foldername, directory_path)

                # 将文件夹添加到 ZIP 文件中
                zipf.write(foldername, arcname=arcname)

                for filename in filenames:
                    # 构建文件的完整路径
                    file_path = os.path.join(foldername, filename)

                    # 构建 ZIP 文件中的相对路径
                    arcname = os.path.relpath(file_path, directory_path)

                    # 将文件添加到 ZIP 文件中
                    zipf.write(file_path, arcname=arcname)

        # 将生成的 ZIP 文件移动到 ./dist 目录中
        os.replace(zip_filename, os.path.join(directory_path, zip_filename))
        print(
            f'Contents of {directory_path} have been compressed to {zip_filename} and placed in ./dist folder.')
    except Exception as e:
        print(f'An error occurred: {str(e)}')

if __name__ == "__main__":
    # 指定要压缩的文件夹路径
    directory_to_compress = '../dist'

    # 指定要创建的 ZIP 文件名
    zip_filename = 'dist.zip'

    # 使用函数将文件夹及其内容压缩成 ZIP 文件并移动到 ./dist 目录中
    zip_directory_contents(directory_to_compress, zip_filename)
